<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Crm\Controller;

use PHPExcel;
use PHPExcel_IOFactory;
use Zend\View\Model\ViewModel;
use Crm\Common\CommonHelper;
use Endroid\QrCode\QrCode;

class VoucherController extends AbstractController
{
    /*
     * 代金券列表
     */
    public function indexAction()
    {
        return new ViewModel();
    }
    
    /*
     * 代金券列表
     */
    public function ajaxVoucherTableAction()
    {
        
        $post = $this->request->getPost()->toArray();
        
        $paginator = $this->getVoucherTypeTable()->getVoucherTypeList($post);
        $result = array(
            'paginator' => $paginator,
        );
        
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)
              ->setTerminal(true);

        return $viewModel;
    }
    public function deleteAction()
    {
        $request = $this->getRequest();
        $vt_id = $request->getPost('vt_id');
        try{
            $this->getVoucherTypeTable()->deleteItem($vt_id);
            $response=array(
                'result' => 'true',
                'reason' => '删除成功！',
            );
            die(json_encode($response));
        }catch (\Exception $e){
            $response=array(
                'result' => 'false',
                'reason' => '系统错误！',
            );
            die(json_encode($response));
        }
    }
    /*
     * 代金券详情
     */
    public function voucherDetailAction()
    {
        $params=$this->getEvent()->getRouteMatch()->getParams();
        $vt_id=isset($params['id'])?$params['id']:'';
        $voucherType =array();
        //$paginator =array();
        $productList =array();
        if($vt_id != ''){
            //$paginator = $this->getVoucherTable()->getVoucherList(array('vt_id'=>$vt_id));
            $voucherType = $this->getVoucherTypeTable()->getByVoucherId($vt_id);
            $productList = $this->getProductTable()->findByOrgId($voucherType['org_id']);
        }
        
        $organizationList = array();
        if(!empty($_SESSION['account']['org_id'])) {
            $organization = $this->getOrganizationTable()->findOne($_SESSION['account']['org_id']);
            $organizationList = array($organization);
        }else{
            $organizationList = $this->getOrganizationTable()->findAll();
        }
        return new ViewModel(array(
            'vt_id' =>$vt_id,
            'organization' =>$organizationList,
            'voucherType' => $voucherType,
            //'paginator' => $paginator,
            'productList' => $productList,
        ));
    }
    public function ajaxQrcodeAction()
    {
        $request = $this->getRequest()->getQuery();
        (int) $id = $request['id'];
        $qrcode_url = $this->getConfigSys()['qrcode_domain'].'/my/scanVoucher/'.$id;
        $qrCode = new QrCode();
        $qrCode ->setText($qrcode_url)
        ->setSize(300)
        ->setPadding(10)
        ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
        ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
        ->setLabelFontSize(16)
        ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ->setErrorCorrection(QrCode::LEVEL_MEDIUM);
    
        header('Content-Type: '.$qrCode->getContentType());
        $qrCode->render();
        die;
    }
    
    
    /*
     * 新增代金券
     */
    public function addVoucherAction()
    {
//         $params=$this->getEvent()->getRouteMatch()->getParams();
//         $vt_id=isset($params['id'])?$params['id']:'';
        $voucherType =array();
        //$paginator =array();
        $productList =array();
//         if($vt_id != ''){
//             //$paginator = $this->getVoucherTable()->getVoucherList(array('vt_id'=>$vt_id));
//             $voucherType = $this->getVoucherTypeTable()->getByVoucherId($vt_id);
//             $productList = $this->getProductTable()->findByOrgId($voucherType['org_id']);
//         }
        
        $organizationList = array();
        if(!empty($_SESSION['account']['org_id'])) {
            $organization = $this->getOrganizationTable()->findOne($_SESSION['account']['org_id']);
            $organizationList = array($organization);
        }else{
            $organizationList = $this->getOrganizationTable()->findAll();
        }
        return new ViewModel(array(
            'vt_id' =>'',
            'organization' =>$organizationList,
            'voucherType' => $voucherType,
            //'paginator' => $paginator,
            'productList' => $productList,
            
        ));
    }
    
    /*
     * 代金券详情列表
     */
    public function ajaxVoucherListAction()
    {
    
        $post = $this->request->getPost()->toArray();
    
        $paginator = $this->getVoucherTable()->getVoucherList($post);
        $result = array(
            'paginator' => $paginator,
        );
    
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)
        ->setTerminal(true);
    
        return $viewModel;
    }
    /*
     * 商品列表  商家联动
     */
    public function ajaxProductListAction()
    {
    
        $post = $this->request->getPost()->toArray();
        $productList = array();
        $productList = $this->getProductTable()->findByOrgId($post['org_id']);
        $viewModel = new ViewModel(array(
            'product_id' => $post['product_id'],
            'productList' => $productList,
        ));
         
        return $viewModel->setTerminal(true);
    }
    public function insertVoucherAction()
    {
        $voucherTypeTable = $this->getVoucherTypeTable();
        $data = $this->request->getPost()->toArray();

        try{
            //$voucherTypeTable->beginTransaction();

            $hasInsert = false;
            while (!$hasInsert){
                $uid = uniqid ("", true );
                $guid = strtoupper ( md5($uid.$data['start_time'].$data['name']) );
                $code = substr($guid, 0,10);
                $result = $this->getVoucherTypeTable()->getByVoucherCode($code);
                if($result === false){
                    $data['vt_code'] = $code;
                    $vt_id = $voucherTypeTable->addItem($data);
                    $hasInsert = true;
                }
            }
            
            
            
            
//             $count = 0;
            
//             while ($count != $data['num']){
//                 $uid = uniqid ("", true );
//                 $guid = strtoupper ( md5($uid.$data['start_time'].$data['name']) );
//                 $code = substr($guid, 0,10);
//                 $result = $this->getVoucherTable()->getVoucherByCode($code);
//                 if($result === false){
//                     $voucher = array(
//                         'vt_id'=>$data['vt_id'],
//                         'code'=>$code,
//                     );
//                     $this->getVoucherTable()->addItem($voucher);
//                     $count += 1;
//                 }
//             }
            //$voucherTypeTable->commit();
        }catch(\Exception $e)
        {
            //die($e);
            $voucherTypeTable->rollBack();
            $this->flashMessenger()->addErrorMessage("代金券生成失败！");
            return $this->redirect()->toRoute('crm/voucher',array('action'=>'voucher-detail'));
        }
        $this->flashMessenger()->addSuccessMessage("代金券生成成功！");
        return $this->redirect()->toRoute('crm/voucher',array('action'=>'voucher-detail','id'=>$vt_id));

    }
    public function updateVoucherAction()
    {
        $voucherTypeTable = $this->getVoucherTypeTable();
        $data = $this->request->getPost()->toArray();

        try{
            $voucherTypeTable->updateItem($data['vt_id'],$data);

            $this->flashMessenger()->addSuccessMessage("代金券修改成功！");
            return $this->redirect()->toRoute('crm/voucher',array('action'=>'voucher-detail','id'=>$data['vt_id']));
        }catch(\Exception $e)
        {
            //die($e);
            $this->flashMessenger()->addErrorMessage("代金券修改失败！");
            return $this->redirect()->toRoute('crm/voucher',array('action'=>'voucher-detail','id'=>$data['vt_id']));
        }
    }
    
    public function excelDetailAction()
    {

        $params=$this->getEvent()->getRouteMatch()->getParams();
        $vt_id=isset($params['id'])?$params['id']:'';
        $outExcelList = array();
        $outExcelList = $this->getVoucherTable()->getOutExcelList(array('vt_id'=>$vt_id));
        $objPHPExcel = new PHPExcel();
        //设置title
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '代金券类型ID')
        ->setCellValue('B1', '代金券名称')
        ->setCellValue('C1', '代金券数量')
        ->setCellValue('D1', '金额')
        ->setCellValue('E1', '开始日期')
        ->setCellValue('F1', '截止日期')
        ->setCellValue('G1', '代金券备注')
        ->setCellValue('H1', '代金券ID')
//         ->setCellValue('I1', '代金券编码')
        ->setCellValue('I1', '绑定用户ID')
        ->setCellValue('J1', '绑定用户姓名')
        ->setCellValue('K1', '使用状态');

        //详细数据
        foreach ($outExcelList as $key=>$recharge){
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A'.($key + 2), $recharge['vt_id'])
            ->setCellValue('B'.($key + 2), $recharge['vt_name'])
            ->setCellValue('C'.($key + 2), $recharge['vt_num'])
            ->setCellValue('D'.($key + 2), $recharge['vt_price'])
            ->setCellValue('E'.($key + 2), $recharge['vt_start_time'])
            ->setCellValue('F'.($key + 2), $recharge['vt_end_time'])
            ->setCellValue('G'.($key + 2), $recharge['vt_remark'])
            ->setCellValue('H'.($key + 2), $recharge['id'])
//             ->setCellValue('I'.($key + 2), $recharge['code'])
            ->setCellValue('I'.($key + 2), $recharge['user_id'])
            ->setCellValue('J'.($key + 2), $recharge['user_name'])
            ->setCellValue('K'.($key + 2), $recharge['has_use']=='0'?'未使用':'已使用');
        }
    
        // Rename worksheet
        $title = isset($outExcelList[0]['vt_name'])?$outExcelList[0]['vt_name']:'代金券明细';
        
        $objPHPExcel->getActiveSheet()->setTitle($title);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); // 生成excel文件 Excel2007
        CommonHelper::browserExport('Excel5', $title.'_'.date('YmdHis').'.xls'); // 输出到浏览器
        $objWriter->save("php://output");
        exit();
    }
    public function excelVoucherAction()
    {
        $outExcelList = array();
        $outExcelList = $this->getVoucherTypeTable()->getOutExcelList();
    
        $objPHPExcel = new PHPExcel();
        //设置title
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '代金券类型ID')
        ->setCellValue('B1', '代金券名称')
        ->setCellValue('C1', '代金券数量')
        ->setCellValue('D1', '金额')
        ->setCellValue('E1', '开始日期')
        ->setCellValue('F1', '截止日期')
        ->setCellValue('G1', '代金券备注');
    
        //详细数据
        foreach ($outExcelList as $key=>$recharge){
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A'.($key + 2), $recharge['vt_id'])
            ->setCellValue('B'.($key + 2), $recharge['vt_name'])
            ->setCellValue('C'.($key + 2), $recharge['vt_num'])
            ->setCellValue('D'.($key + 2), $recharge['vt_price'])
            ->setCellValue('E'.($key + 2), $recharge['vt_start_time'])
            ->setCellValue('F'.($key + 2), $recharge['vt_end_time'])
            ->setCellValue('G'.($key + 2), $recharge['vt_remark']);
        }
    
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('代金券');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); // 生成excel文件 Excel2007
        CommonHelper::browserExport('Excel5', '代金券_'.date('YmdHis').'.xls'); // 输出到浏览器
        $objWriter->save("php://output");
        exit();
    }
}
